<?php


namespace UU\Suite\DingTalk;


use Psr\Http\Message\ServerRequestInterface;
use UU\Suite\Kernel\Contracts\EncryptorInterface;

class Message extends \UU\Suite\Kernel\Message
{
    //
    /**
     */
    public static function createFromRequest(ServerRequestInterface $request, ?EncryptorInterface $encryptor = null): self
    {
        $attributes = json_decode($originContent = strval($request->getBody()->getContents()),true);
        $query = $request->getQueryParams();
        $signature = $query['msg_signature'] ?? $query['signature'] ?? null;

        if ($signature && $ciphertext = $attributes['encrypt'] ?? null) {
            if (!$encryptor) {
                throw new \InvalidArgumentException('$encryptor could not be empty in safety mode.');
            }
            $attributes = json_decode($encryptor->decrypt(
                $ciphertext,
                $signature,
                $query['nonce'],
                $query['timestamp']
            ),true);
        }

        return new static($attributes, $originContent);
    }
}